package com.example.myproject;
import java.io.IOException;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import com.google.appengine.api.datastore.Key;
import com.google.storage.onestore.v3.OnestoreEntity.Path.Element;
import com.sun.xml.internal.txw2.Document;

@PersistenceCapable
public class House {
	
	@PrimaryKey
	@Persistent(valueStrategy=IdGeneratorStrategy.IDENTITY)
	private Key id;
	
	@Persistent
	private String phonoNo,ownerName,emailAddress,homeAddress;
	
	@Persistent
	private Double ltd,lng;
	
	public House(){	
		this.phonoNo="";
		this.ownerName="";
		this.emailAddress="";
		this.ltd=0.0;
		this.lng=0.0;
		this.homeAddress="";
	}
	
	public void setPhonoNo(String phonoNo) {
		this.phonoNo = phonoNo;
	}

	public void setOwnerName(String ownerName) {
		this.ownerName = ownerName;
	}
	
	public void setEmailAddress(String emailAddress) {
		this.emailAddress = emailAddress;
	}
	
	void setLtd(Double ltd) {
		this.ltd = ltd;
	}
	
	void setLng(Double lng) {
		this.lng = lng;
	}
	
	public void setLatLng(String homeAddress){
		
		this.homeAddress = homeAddress;
		if(homeAddress.length()>0){
		DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder;
		try {
			builder = fact.newDocumentBuilder();
	
		org.w3c.dom.Document doc = builder.parse("http://maps.googleapis.com/maps/api/geocode/xml?address=" + homeAddress + "&sensor=false");
		NodeList latlist;
		NodeList lnglist;
		Element xmlElement;
		NodeList status = doc.getElementsByTagName("status");
		Node statusNode = status.item(0);
		String stat = statusNode.getTextContent();
		if(stat.equals("ZERO_RESULTS")){
			ltd = 0.0;
			lng = 0.0;
		}
		else{
		latlist = doc.getElementsByTagName("lat");
		lnglist = doc.getElementsByTagName("lng");

		Node latNode = latlist.item(1);
		Node lngNode= lnglist.item(1);
		ltd = ((Double)(Double.parseDouble(latNode.getTextContent()) + 0.003));
		lng = ((Double)(Double.parseDouble(lngNode.getTextContent()) + 0.002));
		}
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
	}
	
	public double getLat(){
		return ltd;
	}
	
	public double getLng(){
		return lng;
	}	
	
	public String getOwnerName(){
		return ownerName;
	}
}
